package com.aaa.order.service.impl;

import com.aaa.entity.AccountOrder;
import com.aaa.entity.Order;
import com.aaa.order.dao.OrderDao;
import com.aaa.order.feign.CarFeign;
import com.aaa.order.feign.MemberFeign;
import com.aaa.order.service.ALiOrderService;
import com.aaa.pay.vo.PayInfoVO;
import com.aaa.pay.vo.PayResultDTO;
import com.aaa.pay.vo.PayStatusEnum;
import com.aaa.vo.Result;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author 崔灿
 * @Date 2023/03/15 20:25
 * @ClassName ALiOrderServiceImpl
 * @Description
 * @Version 1.0
 */

@Service
public class ALiOrderServiceImpl implements ALiOrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private CarFeign carFeign;

    @Autowired
    private MemberFeign memberFeign;


    @Value("2021000121681568")
    private String appId;

    @Value("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCacoRUYw36HiHEH7N+KsG79EK6CQgFvroa2O+348Lm2MDabQEOA7NRM2DkQd3HaYvB5X084TqpnwyS0skhptZkjrwp4ia7D2wJtzPZVSMdoj/MhYjxichoLDpzpV2pe8yA7410yrbNksq9m25B/6beI2JFCa57csGCJ3JFj7elb0CL/VpxdXKs6xIW2DzYti3CtPyKfuTT1LT5ECGwoxsCtuFN/aTYrhXi43Lvqq6NPF1J2KXBpJ+AhrM7UVKtwhgZxCQ5nqbJFXDk7Up5IAaLG9IUdkzJAZoXNBO4gW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jbbvET9+W8EAF8xDdUf8CgYBKIWAJ6Rnr1/nUeeHvEmt+BQF3nB3Z3i8RnKKUOrweu3kls5BdgIL77E4uZctPm/zlnbTkUOATxNw5VGFTmEh/5MXh7JLALzwWnD4i6Uijj4j/Sk80vEfwaqUaVNaxocmuOFbj74skEdUTuuBEzLWIrpSOeX7ho6ue74msZNqEyQ==")
    private String privateKey;

    @Value("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhB7WohYSe7obk49d9qZsFrhNpwMQwYslHl3I1+SVk2T2RsfXhscwzycvTQm2BtuFHe1aquLWEnsM6iXQSkTWjZrUdnhZ8Y/TJcmNGJTfnQXsVQb2yMLBD9om6A1WnuZvw6ZXveRq42lTUCTd1NK3yBRbWpCkWE3kMRx1LFlVg8MKR9xazC2oadffj5gmadnZ91R8OW2ZGCRfMOS+mGh+5JXGsNyJCeUDlGb7zvxKkWdgVJq/V8DKN3KWLTg/Glp9I4E9/bvm7quN486qJliChupa2Ix14z4d5qSGgRlyOh8kOmXfL762nKhvKgsZmV+7KNF6NXlHUGqSGxQN8veYxwIDAQAB")
    private String publicKey;

    @Value("https://openapi.alipaydev.com/gateway.do")
    private String gateway;

    private AlipayClient alipayClient;

    @PostConstruct
    public void init() {
        alipayClient = new DefaultAlipayClient(gateway,
                appId, privateKey, "json", "utf-8", publicKey, "RSA2");
    }

    @Override
    public Result createALiNative(Order order) {
        //先创建一个支付订单
        order.setState(1);
        order.setAddtime(new Date());
        orderDao.insert(order);
        //获取创建订单的id
        Integer id = order.getId();
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        wrapper.eq("state",1);
        Order order1 = orderDao.selectOne(wrapper);
        if (order1!=null){
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            // 支付请求
            request.setBizContent("{" +
                    "    \"out_trade_no\":\"" + id + "\"," +//商户订单号
                    "    \"total_amount\":\"" + order1.getPreparidAmount() + "\"," +
                    "    \"subject\":\"" + "老六租车" + "当面付" + "\"," +
                    "    \"store_id\":\"00100\"," + // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
                    "    \"timeout_express\":\"500m\"}");//订单允许的最晚付款时间
            AlipayTradePrecreateResponse response = null;
            String qrCode = "";
            try {
                response = alipayClient.execute(request);
                if (response.isSuccess()) {
                    qrCode = response.getQrCode();
                    // 封装支付信息 返回
                    PayInfoVO payInfoVO = new PayInfoVO();
                    payInfoVO.setOrderId(order1.getId());
                    payInfoVO.setShopName("老六租车");
                    payInfoVO.setUrl(qrCode);
                    payInfoVO.setMemberId(order1.getId());
                    payInfoVO.setMoney(order1.getPreparidAmount());
                    return new Result(2000,"支付宝请求成功",payInfoVO);
                }

            } catch (AlipayApiException e) {
                throw new RuntimeException("生成支付宝订单成功");
            }
        }
        return new Result(2000,"支付宝请求失败");
    }

    @Override
    public Result queryPayStatus(Integer id) {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + id + "\"}");
        AlipayTradeQueryResponse response = null;
        PayResultDTO payResultDTO = new PayResultDTO();
        try {
            response = alipayClient.execute(request);
            if (!response.isSuccess()) {
                // 获取支付信息失败
                payResultDTO.setStatus(PayStatusEnum.WAIT_SCANNED.getCode());
                payResultDTO.setMsg("等待扫码");
                return new Result(5000,"支付失败");
            }

            switch (response.getTradeStatus()) {
                case "WAIT_BUYER_PAY":
                    payResultDTO.setStatus(PayStatusEnum.UN_PROCESSED.getCode());
                    payResultDTO.setMsg("已扫码，等待用户支付");
                    break;
                case "TRADE_CLOSED":
                    payResultDTO.setStatus(PayStatusEnum.SHIPPING.getCode());
                    payResultDTO.setMsg("支付已关闭");
                    break;
                case "TRADE_SUCCESS":
                    payResultDTO.setStatus(PayStatusEnum.PROCESSED.getCode());
                    payResultDTO.setAmount(new BigDecimal(response.getTotalAmount()));
                    payResultDTO.setMsg("支付成功");

                    Order order = new Order();
                    order.setState(4);
                    QueryWrapper<Order> wrapper = new QueryWrapper<>();
                    wrapper.eq("id",id);
                    wrapper.eq("state",0);
                    orderDao.update(order,wrapper);
                    // 这里写支付成功的逻辑，例如设置支付时间，订单状态什么的
                    break;
                default:
                    break;
            }
            return new Result(2000,"支付成功",payResultDTO);
        } catch (AlipayApiException e) {
            payResultDTO.setStatus(-1);
            payResultDTO.setMsg("查询订单状态错误:" + e.getErrMsg());
        }
        return new Result(5000,"出错了");
    }

    @Override
    public Result updateStatus(Order order) {
        //根据memberID查询member，减余额
        Integer memberId = order.getMemberId();
        Double accountBalance = order.getPreparidAmount();
        memberFeign.updateAmount(memberId, accountBalance);

        //修改汽车的状态
        Integer carId = order.getCarId();
        System.out.println("carId = " + carId);
        carFeign.updateState(carId);

        //修改优惠券的状态
        Integer couponId = order.getCouponId();
        if (couponId!=-1){
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(date);
            memberFeign.updateState(couponId,format);
            return new Result(2000,"成功",order);
        }

        return new Result(5000,"失败");

    }
}
